// Client Management Plane
package com.google.JT.sockettransfer;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class EMS_agent{
	Socket agentSocket;
	ObjectOutputStream out;
 	ObjectInputStream in;
 	String message;
	EMS_agent(){}
	void run()
	{
			try{
				// Creating a socket to connect to the server
				agentSocket = new Socket("10.0.2.2", 8080);
				System.out.println("Connected to 10.0.2.2 in port 8080");
				
				// Get Input and Output streams
				out = new ObjectOutputStream(agentSocket.getOutputStream());
				out.flush();
				in = new ObjectInputStream(agentSocket.getInputStream());
				
				// Communicating with the server
				do{
					try{
						message = (String)in.readObject();
						System.out.println("server>" + message);
						sendMessage("Hello my server");
						message = "bye";
						sendMessage(message);
					}
					catch(ClassNotFoundException classNot){
						System.err.println("data received in unknown format");
					}
				}while(!message.equals("bye"));
			}
			catch(UnknownHostException unknownHost){
				System.err.println("You are trying to connect to an unknown host!");
			}
			catch(IOException ioException){
				ioException.printStackTrace();
			}
			finally{
				// Closing connection
				try{
					in.close();
					out.close();
					agentSocket.close();
				}
				catch(IOException ioException){
					ioException.printStackTrace();
				}
			}
		}
	void sendMessage(String msg)
	{
		try{
			out.writeObject(msg);
			out.flush();
			System.out.println("client>" + msg);
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
	}
	public static void main(String args[])
	{
		EMS_agent client = new EMS_agent();
		client.run();
	}
}